#include"PriorityQueue.h"

PriorityQueue::PriorityQueue()
{
	/* Post: The PriorityQueue is initialized to be empty. */
	rear = 0;
}

Error_code PriorityQueue::append(const Queue_entry& item)
{
	/*  Post: item is added to the rear of the PriorityQueue and adjust to the proper position by priority field. If the PriorityQueue is full return an Error_code of overflow.*/
	if (rear >= MAX_QUEUE)
		return overflow;
	entry[rear++] = item;
	for (int i = rear - 1; i > 0; i--)  //sort by priority 
	{
		if (entry[i].priority > entry[i - 1].priority)
		{
			Queue_entry temp;
			temp = entry[i];
			entry[i] = entry[i - 1];
			entry[i - 1] = temp;
		}
	}
	return success;
}

bool PriorityQueue::empty()const
{
	/* Post: Return true if the PriorityQueue is empty, otherwise return false. */
	return rear <= 0;  
}

Error_code PriorityQueue::serve()
{
	/* Post: The front of the PriorityQueue is removed. If the PriorityQueue is empty return an Error_code of underflow. */
	if (empty())
		return underflow;
	for (int i = 0; i <= rear - 1; i++)
	{
		entry[i] = entry[i + 1];
	}
	rear--;
	return success;
}

Error_code PriorityQueue::retrieve(Queue_entry& item)const
{
	/*  Post: The front of the PriorityQueue retrieved to the output parameter item. If the PriorityQueue is empty return an Error_code of underflow.  */
	if (empty())
		return underflow;
	item = entry[0];
	return success;
}
